//
//  DACollectedFilesViewController.m
//  DAKnowledge
//
//  Created by 黄健宇 on 16/8/30.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DACollectedFilesViewController.h"
#import "DACollectionFiles.h"
#import "DAWebFileViewController.h"
#import "DANetWorkReachabilityStatus.h"

@interface DACollectedFilesViewController ()<UITableViewDelegate , UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *collectFiles;
@property (nonatomic, strong) NSMutableArray *keys; //存储key值
@property (nonatomic, strong) NSMutableArray *indexArray; //索引数组
@property (nonatomic, strong) NSMutableArray *charactorArray; //A-Z 数组
@property (nonatomic, strong) NSMutableDictionary *userDic;

@end

@implementation DACollectedFilesViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = NO;
    self.keys = [NSMutableArray array];
    self.userDic = [[NSMutableDictionary alloc]init];
    self.navigationItem.title = NSLocalizedString(@"collectedFiles", nil);
    [self refreshData];
    [self createTableView];
    [self.tableView.mj_header beginRefreshing];
      // Do any additional setup after loading the view.
}

- (void)refreshData{
    [[DACollectionFiles shareDACollectionFiles]updateWithUserID:self.userID Block:^(NSMutableArray *array) {
        self.collectFiles = array;
       //  NSLog(@"数据 %@",self.collectFiles);
        [self arraySort];
      //  NSLog(@"首字母 %@",self.keys);
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    }];

}

- (void)createTableView{
    self.tableView.delegate  = self ;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.tableView.sectionIndexColor = [UIColor supportGreenColor];
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = [UIView new];
    
    //Header
    MJRefreshGifHeader *header =[MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    NSMutableArray *refreshImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"page%ld@3x", (unsigned long)i]];
        [refreshImages addObject:image];
    }
    NSMutableArray *normalImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"stay%ld@3x", (unsigned long)i]];
        [normalImages addObject:image];
    }
    UIImage *image = [UIImage imageNamed:@"stay21@3x"];
    [normalImages insertObject:image atIndex:0];
    
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStateRefreshing];
    [header setImages:normalImages forState:MJRefreshStateIdle];
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStatePulling];
    
    header.lastUpdatedTimeLabel.hidden= YES;//如果不隐藏这个会默认 图片在最左边不是在中间
    header.stateLabel.hidden = YES;
    self.tableView.mj_header = header;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//获取首字母
- (void)arraySort{
    // self.indexArray = [NSMutableArray array];
    [self.keys removeAllObjects];
    self.charactorArray = [NSMutableArray array];
    for (char a = '0'; a <= '9'; a++) {
        [self.charactorArray addObject:[NSString stringWithFormat:@"%c",a]];
    }
    for (char a = 'A'; a <= 'Z'; a++) {
        [self.charactorArray addObject:[NSString stringWithFormat:@"%c",a]];
    }
    for (DACollectionFiles *collectFiles in self.collectFiles) {
        NSString *key = [self firstCharactor:collectFiles.fileName];
        [self.keys addObject:key];
    }
    for (NSString *key in self.keys) {
        NSMutableArray *arr = [NSMutableArray array];
        [self.userDic setObject:arr forKey:key];
    }
    for (DACollectionFiles *collectFiles in self.collectFiles) {
        NSString *key = [self firstCharactor:collectFiles.fileName];
        //NSLog(@"file名 %@",userFileModel.fileName);
        [self.userDic[key] addObject:collectFiles];
    }
    self.indexArray = [[self.userDic.allKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]mutableCopy];
    if ([self.indexArray containsObject:@"#"]) {
        [self.indexArray removeObject:@"#"];
        [self.indexArray addObject:@"#"];
    }
    [self.tableView reloadData];
}
// 获取首字母方法
- (NSString *)firstCharactor:(NSString *)string{
    NSMutableString *str = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, YES);
    NSString *largeStr = [str capitalizedString];
    NSString *firstStr;
    if (string.length != 0) {
        firstStr = [largeStr substringToIndex:1];
    }
    BOOL isContain = [self.charactorArray containsObject:firstStr];
    if (isContain == NO || [firstStr isEqualToString:@""]) {
        firstStr = @"#";
    }
    return firstStr;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSLog(@"TABEVIEWCELL");
    return self.indexArray.count;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return self.indexArray[section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSString *key = self.indexArray[section];
    NSArray *arr = self.userDic[key];
    return  arr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DAFileListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"collectedFile"];
    if (cell == nil) {
        cell = [[DAFileListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"collectedFile"];
    }
    NSString *key = self.indexArray[indexPath.section];
    NSArray *arr = self.userDic[key];
    DACollectionFiles *file = arr[indexPath.row];
    
    
    NSString *name = [NSString stringWithFormat:@"file_%@.png",file.fileExtend];
    UIImage *image = [UIImage imageNamed:name];
    cell.fileNameLabel.text = file.fileName;
    cell.fileImageView.image = image;
    cell.fileIntroduction.text = file.fileType;
    cell.fileIntroduction.textColor = [UIColor colorWithHexString:timeColor];
    
    //处理文件大小
    int fileSize = [file.fileSize intValue];
    float fileSizeK = 0.0;
    float fileSizeM = 0.0;
    if (fileSize > 999 && fileSize < 999*1024) {
        fileSizeK = fileSize/1024.0;
        cell.fileSize.text = [NSString stringWithFormat:@"%.2fK",fileSizeK];
    }else if (fileSize >= 999*1024 ){
        fileSizeM = fileSize/(1024.0*1024.0);
        cell.fileSize.text = [NSString stringWithFormat:@"%.2fM",fileSizeM];
    }else{
        cell.fileSize.text = [NSString stringWithFormat:@"%dB",fileSize];
    }
    cell.fileSize.textColor = [UIColor colorWithHexString:timeColor];
    
    //进度条处理
    file.isDownloading = NO;
    if(file.isDownloading == NO){
        cell.progress.hidden = YES;
        cell.progress.progress = 0;
    }else{
        cell.progress.hidden = NO;
    }
    
    // 下载完成之后   显示已下载的图表
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [path objectAtIndex:0];
    if ([self isFileExist:[NSString stringWithFormat:@"%@.%@",file.folderName,file.fileExtend] inPath:documentsDirectory]) {
        cell.downLoadCompleteImage.image = [UIImage imageNamed:@"complete@3x"];
    }else{
        cell.downLoadCompleteImage.image = nil;
    }
    
    
    return cell;
}

//Cell左划响应事件
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSString *key = self.indexArray[indexPath.section];
//    NSMutableArray *arr = [self.userDic objectForKey:key];
//    DAUserFileModel *model = [arr objectAtIndex:indexPath.row];

    NSString *key = self.indexArray[indexPath.section];
    NSArray *arr = self.userDic[key];
    DACollectionFiles *file = arr[indexPath.row];
    BOOL flag = false;
    
    flag = [[DACollectionFiles shareDACollectionFiles] isContainCollectionsWith:file.fileID];
    
    
    if (!flag) {
        //收藏按钮
        UITableViewRowAction *collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"收藏" handler:^(UITableViewRowAction *_Nonnull action, NSIndexPath * _Nonnull indexPath){
            NSLog(@"收藏");
            NSDictionary *dic;
            NSString *url = DACollectionFile;
            dic = @{@"collectUserID":self.userID , @"collectFolderName":file.folderName};
            
            [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
                if (result) {
                    NSLog(@"结果 %@",result);
                    //NSLog(@"收藏成功!");
                    [SVProgressHUD showSuccessWithStatus:@"收藏成功"];
                    //[self.collectFiles addObject:model];
                    [[DACollectionFiles shareDACollectionFiles] updateWithUserID:self.userID Block:^(NSMutableArray *array) {
                        self.collectFiles = array;
                    }];
                    if (tableView == self.tableView) {
                        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }else{
                        [self.searchDisplayController.searchResultsTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }
                }else{
                    // NSLog(@"收藏失败!");
                    [SVProgressHUD showErrorWithStatus:@"收藏失败"];
                }
            }];
            //NSLog(@"用户 : %@  文件 : %@",self.userID,model.filefolderName);
        }];
        collectRowAction.backgroundColor = [UIColor orangeColor];
        //  [self prepareCollectFiles];
        return  @[collectRowAction];
    }else{
        //取消收藏按钮
        UITableViewRowAction *collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"取消收藏" handler:^(UITableViewRowAction *_Nonnull action, NSIndexPath * _Nonnull indexPath){
            NSLog(@"取消收藏");
            NSDictionary *dic;
            NSString *url = DACancelCollectionFile;
            dic = @{@"collectUserID":self.userID , @"collectFolderName":file.folderName};
            
            [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
                NSLog(@"结果 %@",result);
                if (result) {
                    //NSLog(@"收藏成功!");
                    [SVProgressHUD showSuccessWithStatus:@"取消收藏成功"];
                    //[self.collectFiles removeObject:trans];
                    [[DACollectionFiles shareDACollectionFiles]updateWithUserID:self.userID Block:^(NSMutableArray *array) {
                        self.collectFiles = array ;
                    }];
                    if (tableView == self.tableView) {
                        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }else{
                        [self.searchDisplayController.searchResultsTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }
                }else{
                    NSLog(@"取消收藏失败!");
                    [SVProgressHUD showErrorWithStatus:@"取消收藏失败"];
                }
            }];
        }];
        collectRowAction.backgroundColor = [UIColor orangeColor];
        // [self prepareCollectFiles];
        return @[collectRowAction];
    }
    //return tabItems;
}




//点击CELL
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *key = self.indexArray[indexPath.section];
    NSArray *arr = [self.userDic objectForKey:key];
    DACollectionFiles *file = [arr objectAtIndex:indexPath.row];
    DAFileListTableViewCell *cell = [[DAFileListTableViewCell alloc]init];
    cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    //文件保存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, file.folderName,file.fileExtend];
    
    
    //判断文件在本地是否存在
    if(file.isDownloading == YES){
        NSLog(@"正在下载");
    }else{
        
        BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@",file.folderName,file.fileExtend] inPath:documentsDirectory];
        if (isExist) {
            NSLog(@"文件存在可以直接打开");
            DAWebFileViewController *webFile = [[DAWebFileViewController alloc]init];
            webFile.fileUrl = filePath;
            webFile.fileID = file.fileID;
            webFile.filefolderName = file.folderName;
            webFile.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:webFile animated:YES];
        }else{
            //下载文件
            //判断网络连接
            [DANetWorkReachabilityStatus isNetWorkConnectWithBlock:^(BOOL isConnect){
                if (isConnect) {
                    NSLog(@"下载文件");
                    cell.progress.hidden = NO;
                    file.isDownloading = YES;
                    [NSThread detachNewThreadSelector:@selector(downloadFileOnBackground:) toTarget:self withObject:indexPath];
                }else{
                    NSString *str = NSLocalizedString(@"NoNetWorkCouldNotDownload", nil);
                    [SVProgressHUD showErrorWithStatus:str];
                }
            }];
        }
    }


    
    
}
#pragma mark - 判断沙盒里是否有这个文件
-(BOOL)isFileExist:(NSString *)fileName inPath:(NSString *)path{
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    //  NSLog(@"该文件：%@",result?@"有！！":@"不存在");
    return result;
}

#pragma marks - fileListCell下载
- (void)downloadFileOnBackground:(NSIndexPath *)indexPath{
    NSString *key = self.indexArray[indexPath.section];
    NSArray *arr = [self.userDic objectForKey:key];
    DACollectionFiles *file = [arr objectAtIndex:indexPath.row];
    DAFileListTableViewCell *cell = [[DAFileListTableViewCell alloc]init];
    cell = [self.tableView cellForRowAtIndexPath:indexPath];
    NSLog(@"MODEL %@",file.folderName);
    //文件保存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"文件保存路径 %@",documentsDirectory);
    
    //文件下载路径
    NSString *str = file.fileUrl;
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)str, NULL, NULL,  kCFStringEncodingUTF8 ));
    NSURL *url = [NSURL URLWithString:encodedString];
    // NSURL *url= [NSURL URLWithString:[NSString stringWithFormat:@"http://10.2.8.224/DAKnowledgeUpload/uploads/Tset20160805031214/Tset.pdf"]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString  *fullPath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, file.folderName,file.fileExtend];
    // NSURL *url = [NSURL URLWithString:@"http://www.abc.com/test.mp4"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *task =
    //    [manager downloadTaskWithRequest:request
    //                            progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    //                                return [NSURL fileURLWithPath:fullPath];
    //                            }
    //                   completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    //
    //                   }];
    
    [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        CGFloat count = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        dispatch_async(dispatch_get_main_queue(), ^{
            [cell.progress setProgress:count animated:YES];
        });
        //  NSLog(@"下载进度 %f",count);
        //    if (self.isFinish == NO) {
        //            [SVProgressHUD  showProgress:count];
        //        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        cell.progress.hidden = YES;
        cell.downLoadCompleteImage.image = [UIImage imageNamed:@"complete@3x"];
        file.isDownloading = NO;
        //[SVProgressHUD dismiss];
        // [self creatPreview];
    }];
    [task resume];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
